from rest_framework import serializers

from course import models


class CategorySer(serializers.ModelSerializer):
    class Meta:
        model = models.Category
        fields = ["id", "name"]


class CategorySerializer(serializers.ModelSerializer):
    children = CategorySer(many=True)

    class Meta:
        model = models.Category
        fields = '__all__'


class CateSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()  # 关系序列化自定义的函数

    def get_children(self, obj):  # 当前类的实例
        # 判断当前obj是否有子类
        if obj.children.all().exists():
            return CategorySerializer(obj.children.all(), many=True).data
        else:
            return []

    class Meta:
        model = models.Category
        fields = '__all__'
